package jwtoken

import (
	"errors"
	"time"

	jwt "github.com/dgrijalva/jwt-go"
)

const (
	ExpireHour = 2
	Secret     = "bbsserve"
)

// MySecret 定义JWT TOKEN的加密盐
var MySecret = []byte(Secret)

type MyClaims struct {
	jwt.StandardClaims
	Username string `json:"username"`
	UserID   int    `json:"user_id"`
	Avatar   string `json:"avatar"`
}

// 生成JWT
func GenToken(username, avatar string, userId int) (string, error) {
	// 创建一个我们自己的声明
	c := MyClaims{
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(ExpireHour * time.Hour).Unix(),
		},
		username,
		userId,
		avatar,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	return token.SignedString(MySecret)
}

// 解析JWT
func ParseToken(tokenString string) (*MyClaims, error) {
	// 解析token
	token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (i interface{}, err error) {
		return MySecret, nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*MyClaims); ok && token.Valid { // 校验token
		return claims, nil
	}
	return nil, errors.New("invalid token")
}
